#include <cstdio>
#include <string.h>
#include <ctime>
#include <cstdlib>

#include "decisiontree.h"

const size_t m_small = 4;

const char* trainingFile = "..\\Data\\training.csv";
const char* testFile = "..\\Data\\test.csv";
const bool addSecondField = true;

Data all;
vector<string> v;
char s[9230];

void readData() {
  freopen( trainingFile, "r", stdin );
  gets( s );
  int it = 0;
  while ( gets( s ) ) {
    it++;
    if ( it%10000 == 0 ) fprintf( stderr, "%d read...\n", it );
    int n = strlen( s );
    s[n++] = ',';
    string cur = "";
    v.clear();
    forn( i, n )
      if ( s[i] == ',' ) v.pb( cur ), cur = "";
      else cur += s[i];
    //cur = v[14].length() > 4 ? v[14].substr( 0, (int)v[14].length()-4 ) : "0";
    //v[14] = "V" + cur;
    all.pb( v );
  }
  fclose( stdin );
  fprintf( stderr, "Data read.\n" );
}

int countDifferent( size_t id ) {
  set<string> ss;
  forn( i, all.size() )
    ss.insert( all[i][id] );
  return ss.size();
}

int main(int argc, char* argv[]) {

  if ( argc != 3 ) {
    fprintf( stderr, "Usage: randomforest <seed> <number of trees>\n" );
    return 0;
  }

  int seed;
  sscanf( argv[1], "%d", &seed );
  srand( seed );

  int trees;
  sscanf( argv[2], "%d", &trees );

  readData();
  vector<DecisionTree*> randomForest;
  Data currentData;

  for ( size_t i = 0; i < all[0].size(); i++ )
    isNumber.pb( isPositiveNumber( all[0][i] ) && countDifferent(i) > 22 );

  for ( size_t i = 2; i < all[0].size(); i++ )
    if (use[i] && (isNumber[i] || countDifferent(i) < 22) ) {
      vv.pb( i );
//      fprintf( stderr, "%d -> %d\n", i, (int)isNumber[i] );
    }

  fprintf( stderr, "vv.size() = %d\n", vv.size() );

  fprintf( stderr, "Data read, %.3f\n", clock() * 1.0 / CLOCKS_PER_SEC );
       
  forn( i, trees ) {
    currentData.clear();
    random_shuffle( vv.begin(), vv.end() );
    forn( j, all.size() )
      currentData.pb( all[ R() % all.size() ] );
    nodes = 0;
    randomForest.pb( buildDecisionTree( currentData, m_small, 0 ) );
    fprintf( stderr, "tree %d was grown, %d nodes\n", i+1, nodes );
  }

  fprintf( stderr, "Trees are grown, %.3f\n", clock() * 1.0 / CLOCKS_PER_SEC );
  
  freopen( testFile, "r", stdin );
  printf( "RefId,IsBadBuy\n" );
  gets( s );
  while ( gets( s ) ) {
    int n = strlen( s );
    s[n++] = ',';
    string cur = "";
    v.clear();
    forn( i, n )
      if ( s[i] == ',' ) {
        v.pb( cur );
        cur = "";
        if ( addSecondField ) if ( v.size() == 1 ) v.pb( "0" );
      }
      else cur += s[i];

    double ans = 0;
    forn( i, randomForest.size() )
      ans += randomForest[i]->classify( v );
    ans /= randomForest.size();

    printf( "%s,%.5f\n", v[0].c_str(), ans );
  }
  fclose( stdin );
  return 0;
}
                                                 
